Python中的多进程并行简明教程 | 您所在的位置:网站首页 › pyrhon 多进程 › Python中的多进程并行简明教程 |
1. 什么是多进程并行
一般来说,多进程意味着并行运行两个或者多个任务。在Python中我们可以使用python内置的multiprocessing模块来实现这一功能。 我们来举个栗子,假设我们需要运送十个快递从A点到B点,一个快递员一次只能运送一个快递花费时间为十秒钟,如果我们程序是顺序运行的,也就是说完成这项任务我们需要让一个快递员运送十次,那么此时完成这项任务的时间为一百秒;但是如果我们采用多进程处理,假设我们开十个线程,也就意味着此时我们可以同时拥有十个快递员来并行工作,这时我们完成这项任务的耗时仅需要十秒钟即可。 2. 多进程vs多线程
讲了这么多文字,很多童鞋可能还是云里雾里。那么我们来举个栗子,从代码层面进行理解吧。。。 3.1 顺序执行假设我们的搬运逻辑用代码实现如下: def long_running_function(box_index): time.sleep(10) print("move box {} from A to B ...".format(box_index)) return如果我们使用顺序执行的方式,也就是让一个快递员搬运十次,那么此时的代码逻辑如下: def test1(): time1 = time.time() for index in range(0, 10): long_running_function(index) time2 = time.time() print("time consume {} s".format(time2-time1))上述模拟代码的输出如下: move box 0 from A to B ... move box 1 from A to B ... move box 2 from A to B ... move box 3 from A to B ... move box 4 from A to B ... move box 5 from A to B ... move box 6 from A to B ... move box 7 from A to B ... move box 8 from A to B ... move box 9 from A to B ... time consume 100.050865650177 s 3.2 多进程并行执行为了实现多进程,我们需要引入multiprocessing包,同时利用Process创建子进程,利用start来启动子进程,利用join函数实现阻塞住主进程等待子进程结束。 上述搬运箱子多进程方式代码实现如下: import time import multiprocessing def test2(): time1 = time.time() _processes = [] for index in range(0, 10): _process = multiprocessing.Process(target=long_running_function, args=(index,)) _process.start() _processes.append(_process) for _process in _processes: _process.join() time2 = time.time() print("time consume {} s".format(time2 - time1))上述模拟代码的输出如下: move box 0 from A to B ... move box 8 from A to B ... move box 7 from A to B ... move box 3 from A to B ... move box 2 from A to B ... move box 9 from A to B ... move box 5 from A to B ... move box 1 from A to B ... move box 6 from A to B ... move box 4 from A to B ... time consume 10.547523975372314 s 4. 参考本文重点参考了以下链接,详情请戳。。。 链接一 链接二 5. 总结本文简单介绍了Python中使用multiprocessing来实现多进程并行,并和程序顺序执行做了相应的对比,并给出了相应的代码实现。 您学废了嘛?
|
CopyRight 2018-2019 实验室设备网 版权所有 |